package com.letv.android.client.webview;

import java.util.HashMap;
import java.util.Map;

import com.letv.ads.util.IAdJSBridge;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebView;

import com.letv.core.db.PreferencesManager;
import com.letv.core.utils.LogInfo;

/**
 * Created by liuxingxing on 14-7-30.
 * WebView与JS相互调用的工具类
 */
public class JSBridgeUtil implements IAdJSBridge{
    private JavaScriptinterface mJavaScriptinterface;
    private static WebView transparentWebView;
    private WebView mWebView;
    private static JSBridgeUtil jsBridgeUtil;

    private JSBridgeUtil() {
    }

    public JavaScriptinterface getJavaScriptinterface() {
        return mJavaScriptinterface;
    }

    public void setJavaScriptinterface(JavaScriptinterface javaScriptinterface) {
        this.mJavaScriptinterface = javaScriptinterface;
    }

    public static WebView getTransparentWebView(Context context) {
        if (transparentWebView == null) {
            transparentWebView = new WebView(context);
        }
        return transparentWebView;
    }

    public static JSBridgeUtil getInstance() {
        if (jsBridgeUtil == null) {
            jsBridgeUtil = new JSBridgeUtil();
        }
        return jsBridgeUtil;
    }

    public void setJSBridge(Activity activity, WebView webView, Handler handler, View root) {
        this.mWebView = webView;
        JavaScriptinterface obj = new JavaScriptinterface(activity, mWebView, root);
        obj.setHandler(handler);
        mWebView.addJavascriptInterface(obj, "LetvJSBridge_For_Android");//JavaScriptinterface <---> android
        setJavaScriptinterface(obj);
    }

    public void unRegisterAllObservers() {
        getJavaScriptinterface().removeAllObservers();
    }

    /**
     * {
     'username'://用户,
     'email'://邮箱,
     'nickname':,用户昵称
     'ssouid':,//ssouid
     'userlevel':/用户级别 0普通会员 1 PC版会员 2 TV版会员
     'lasttime'://服务有效期截至时间
     }
     */

    /**
     * 登录结束之后从sharePreference中获取User信息反馈给JS
     * 问题：若登录失败，不做任何操作吗？
     *
     * @param loginResult
     */
    public void loginCallBack(boolean loginResult) {
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("username", PreferencesManager.getInstance().getUserName());
            map.put("nickname", PreferencesManager.getInstance().getNickName());
            map.put("email", PreferencesManager.getInstance().getEmail());
            map.put("ssouid", PreferencesManager.getInstance().getSsouid());
            map.put("userlevel", PreferencesManager.getInstance().getVipLevel());
            if (1 == PreferencesManager.getInstance().getVipLevel()) {//普通会员
                map.put("lasttime", PreferencesManager.getInstance().getVipCancelTime());
            } else if (2 == PreferencesManager.getInstance().getVipLevel()) {//高级会员
                map.put("lasttime", PreferencesManager.getInstance().getSeniorVipCancelTime());
            }
            JSONObject jsonObject = new JSONObject(map);
            final String callString = "javascript:LetvJSBridge.fireEvent('onlogin','" + jsonObject.toString() + "')";
            LogInfo.log("lxx", "loginCallBack 第二次调用 callString: " + callString);
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    //add by zlb & wlx
                    if (mWebView == null || TextUtils.isEmpty(callString)) {
                        return;
                    }
                    //end
                    LogInfo.log("lxx", "loginCallBack, reload,url: " + mWebView.getUrl());
                    mWebView.loadUrl(callString);
                    mWebView.reload();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 解析JS传来的Json串
     * 注：[{"name":{...}},"callback_id":"...","callback":"...","func":"..."]，此格式是固定的，但是"name"字段的值每个方法都不一样
     */
    public JSInBean parseJsonArray(String jsonString) {
        JSInBean jsInBean = new JSInBean();
        try {
            JSONArray ja = new JSONArray(jsonString);
            JSONObject jo = ja.getJSONObject(0);
            jsInBean.setName(jo.getString("name").trim());
            jsInBean.setCallback_id(jo.getString("callback_id").trim());
            jsInBean.setCallback(jo.getString("callback").trim());
            jsInBean.setFunc(jo.getString("func").trim());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        LogInfo.log("lxx", "parseJsonArray jsInBean: " + jsInBean);
        return jsInBean;
    }

}
